import { Request, Response } from 'express';
import shopService, { ShopGoodsItem } from '../../services/shop.service'

export class Controller {
    // 获取购物车
    get(req: Request, res: Response): void {
        let uid = (req.headers as any).user.id
        shopService.getShopCar(uid).then((result)=>{
            res.status(200).json({ msg: 'ok', data: result })
        }).catch((error)=>{
            res.status(200).json({ msg: 'error', error: error })
        })
    }
    // 添加商品到购物车
    add(req: Request, res: Response): void {
        // 解析请求参数
        let gid = Number(req.query.gid as string)
        let count = Number(req.query.count as string)
        let uid = (req.headers as any).user.id
        // 调用服务方法
        shopService.addGoodsToShopCar(uid, {
            gid,
            count
        }).then(()=>{
            res.status(200).json({ msg: 'ok' })
        }).catch((error)=>{
            res.status(200).json({ msg: 'error', error: error })
        })
    }
    // 更新购物车
    update(req: Request, res: Response): void {
        // 解析参数
        let uid = (req.headers as any).user.id
        let goodsList:ShopGoodsItem[] = []
        req.body.goods.forEach((element: any) => {
            goodsList.push({
                gid: element.item.id,
                count: element.count
            })
        });
        shopService.updateShopCar(uid, goodsList).then(()=>{
            res.status(200).json({ msg: 'ok' })
        }).catch((error)=>{
            res.status(200).json({ msg: 'error', error: error })
        })
    }
}
export default new Controller();